using System.Xml;

namespace RealDolmen.Helpers
{
    public class XmlHelper
    {
        #region GetElementText
        public static string GetElementText(XmlNode node, object name)
        {
            XmlElement element = node[name.ToString()];
            if (element != null)
                return element.InnerText;
            else
                return null;
        } 
        #endregion // GetElementText

        #region GetAttribute
        public static string GetAttribute(XmlNode node, object name)
        {
            return GetAttribute(node, name.ToString());
        }
        public static string GetAttribute(XmlNode node, string name)
        {
            XmlAttribute xmlAttribute =
                node.Attributes[name];
            if (xmlAttribute == null)
                return null;
            else
                return xmlAttribute.Value;
        }
        public static string GetAttribute(XmlNode node, object name, string defaultString)
        {
            return GetAttribute(node, name.ToString(), defaultString);
        }
        public static string GetAttribute(XmlNode node, string name, string defaultString)
        {
            string val = GetAttribute(node, name);
            if (val == null)
                val = defaultString;
            return val;
        } 
        #endregion // GetAttribute

        #region Merge
        public static string Merge(string baseXml, string updateXml)
        {
            XmlDocument xmlDocBase = new XmlDocument();
            xmlDocBase.LoadXml(baseXml);
            XmlDocument xmlDocUpdate = new XmlDocument();
            xmlDocUpdate.LoadXml(updateXml);

            return Merge(xmlDocBase, xmlDocUpdate.DocumentElement).OuterXml;
        }

        public static XmlNode Merge(XmlDocument xmlBaseDoc, XmlNode xmlUpdate)
        {
            return Merge(xmlBaseDoc.DocumentElement, xmlBaseDoc, xmlUpdate);
        }
        private static XmlNode Merge(XmlNode xmlBase, XmlDocument xmlBaseDoc, XmlNode xmlUpdate)
        {
            XmlNode xmlMerged = xmlBase.CloneNode(true);

            foreach (XmlAttribute attribute in xmlUpdate.Attributes)
            {
                XmlAttribute attMerged = xmlMerged.Attributes[attribute.Name];
                if (attMerged == null)
                    xmlMerged.Attributes.Append(xmlBaseDoc.ImportNode(attribute, false) as XmlAttribute);
                else
                    attMerged.Value = attribute.Value;
            }
            return xmlMerged;
        } 
        #endregion // Merge
    }
}
